<template>
  <div class="settings-page">
    <div class="container">
      <el-card class="settings-container">
        <h2 class="settings-title">账号设置</h2>
        
        <el-form 
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="100px"
          size="large"
          class="settings-form">
          
          <!-- 头像上传 -->
          <div class="avatar-uploader">
            <el-upload
              class="avatar-upload"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="basicForm.avatarUrl" :src="basicForm.avatarUrl" class="avatar">
              <img v-else-if="userInfo?.avatarUrl" :src="userInfo.avatarUrl" class="avatar">
              <img v-else :src="defaultAvatar" class="avatar">
            </el-upload>
            <div class="upload-tip">点击更换头像</div>
          </div>
          
          <el-form-item label="用户名" prop="username">
            <el-input v-model="basicForm.username" disabled autocomplete="off"></el-input>
          </el-form-item>
          
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="basicForm.nickname" autocomplete="off"></el-input>
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="basicForm.email" autocomplete="off"></el-input>
          </el-form-item>
          
          <el-form-item label="电话" prop="phone">
            <el-input v-model="basicForm.phone" autocomplete="off"></el-input>
          </el-form-item>
          
          <el-form-item label="地址" prop="address">
            <el-input type="textarea" v-model="basicForm.address" :rows="3" autocomplete="off"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" size="large" @click="saveBasicInfo">保存修改</el-button>
          </el-form-item>
        </el-form>

        <!-- 修改密码 -->
        <div class="settings-section">
          <h3 class="section-title">修改密码</h3>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            size="large"
            class="settings-form">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password"
                placeholder="请输入当前密码"
                show-password>
              </el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password"
                placeholder="请输入新密码"
                show-password>
              </el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password"
                placeholder="请再次输入新密码"
                show-password>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="large" @click="changePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()
// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 表单ref
const basicFormRef = ref(null)
const passwordFormRef = ref(null)
const userName = localStorage.getItem("username")

// 用户信息
const userInfo = ref({
  avatarUrl: defaultAvatar,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  address: ''
})

// 基本信息表单
const basicForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  address: '',
  avatarUrl: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单校验规则
const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 3, message: '密码不能少于3个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 3, message: '密码不能少于3个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 上传地址
const uploadUrl = 'http://localhost:9090/file/upload'

// 生命周期钩子
onMounted(() => {
  fetchUserInfo()
})

// 获取用户信息
const fetchUserInfo = async () => {
  if (userName === null) {
    ElMessage.warning('未登录,请先登录')
    router.push('/')
    return
  }
  try {
    const res = await request.get(`/user/info/${userName}`)
    if (res.data.code === '200') {
      const data = res.data.data
      // 确保所有字段都有默认值
      userInfo.value = {
        avatarUrl: data.avatarUrl || defaultAvatar,
        username: data.username || '',
        nickname: data.nickname || '',
        email: data.email || '',
        phone: data.phone || '',
        address: data.address || ''
      }
      Object.assign(basicForm, {
        username: data.username || '',
        nickname: data.nickname || '',
        email: data.email || '',
        phone: data.phone || '',
        address: data.address || '',
        avatarUrl: data.avatarUrl || defaultAvatar
      })
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 头像上传前的校验
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPGOrPNG && isLt2M
}

// 头像上传成功的回调
const handleAvatarSuccess = async (res) => {
  try {
    // 更新头像URL
    basicForm.avatarUrl = res
    
    // 立即更新用户信息
    const updateRes = await request.post('/user/update', basicForm)
    if (updateRes.data.code === '200') {
      ElMessage.success('头像更新成功')
      // 重新获取用户信息以确保数据同步
      await fetchUserInfo()
    } else {
      ElMessage.error(updateRes.data.msg || '头像更新失败')
    }
  } catch (error) {
    console.error('更新头像失败:', error)
    ElMessage.error('头像更新失败，请稍后重试')
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/user/update', basicForm)
        
        if (res.data.code === '200') {
          ElMessage.success('保存成功')
          
        } else {
          ElMessage.error(res.data.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存用户信息失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    }
  })
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/user/password', {
          password: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
          username: userName
        })
        
        if (res.data.code === '200') {
          ElMessage.success('密码修改成功')
          
          // 清空表单
          passwordForm.oldPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
          passwordFormRef.value.resetFields()
          
          // 清除所有本地存储
          localStorage.clear()
          
          router.push('/')
          // 发送事件通知父组件关闭登录弹窗并重新登录
          // window.parent.postMessage({ type: 'logout' }, '*')
          
          // 刷新页面
          window.location.reload()
        } else {
          ElMessage.error(res.data.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改失败，请稍后重试')
      }
    }
  })
}
</script>

<style scoped>
.settings-page {
  padding: 40px 0;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.settings-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.settings-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  color: #303133;
}

.settings-section {
  margin-top: 50px;
}

.section-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #303133;
}

.avatar-uploader {
  text-align: center;
  padding-bottom: 30px;
}

.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
  transform: scale(1.02);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.settings-form {
  max-width: 100%;
}

.settings-form :deep(.el-input__wrapper) {
  padding: 4px 15px;
}

.settings-form :deep(.el-input__inner) {
  height: 40px;
  font-size: 14px;
}

.settings-form :deep(.el-textarea__inner) {
  padding: 8px 15px;
  font-size: 14px;
}

.settings-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

@media screen and (max-width: 768px) {
  .settings-container {
    margin: 0 20px;
    padding: 20px;
  }
  
  .settings-title {
    font-size: 24px;
    margin-bottom: 30px;
  }
  
  .section-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
}
</style> 